'''
Created on Sep 14, 2012

@author: thomas_dao
'''
from web import base
from web.base import BaseHandler
from web import urls
from kid import util
import json
import logging
from google.appengine.ext import ndb
from app import article_async, board_async, note_async, user_async
from kid import jinja_lib
from entity.entity import Board

class UserPageHandler(BaseHandler):
    @ndb.synctasklet
    def get(self, author_id):
        """
        user is current user
        author is the page that all the user_boards belong to
        user and author is not the same. An user can view page
        of other author
        """
        env = jinja_lib.jinja_environment()
        template = env.get_template('user-page.html')
        author_key = ndb.Key("User", int(author_id))
        user_key = util.get_current_user_key()
        user = None
        
        board_id = self.request.params.get('board_id')
        board_key = None
        if board_id:
            board_key = ndb.Key(Board, int(board_id))
        else:
            board_key = yield board_async.get_default_board_key(author_key)
                    
        values = {}
        (notes, 
         articles, 
         user_boards, 
         author) = yield (board_async.get_notes_by_board(board_key),
                          article_async.get_by_board(board_key), 
                          board_async.get_all(author_key),
                          author_key.get_async())
         
        # Replace user with author and first note with author note
        article_list = util.ndb_to_list(articles)
        author_dict = util.ndb_to_dict(author)
        for i in xrange(len(article_list)):
            article_list[i]['first_note'] = util.ndb_to_dict(notes[i])
            article_list[i]['author'] = author_dict
                  
        values['articles'] = article_list
        values['articles_json'] = json.dumps(article_list)
        values['author'] = author_dict
        values['author_json'] = json.dumps(author_dict)
        values['user_boards'] = user_boards
        values['boards_json'] = json.dumps(util.ndb_to_list(user_boards))

        if user_key:
            (user, all_notes, user_boards, followees) = yield (user_key.get_async(), 
                                   note_async.get_all_async(user_key, projection=['article']),
                                   board_async.get_all(user_key),
                                   user_async.get_followees(user_key))
        
        # Display current user info
        values['user'] = {}
        if user:
            bookmarkArticles = [x.article for x in all_notes]
            values['user'] = util.ndb_to_dict(user)
            values['bookmark_articles'] = util.ndb_to_list(bookmarkArticles)
            values['followees_json'] = json.dumps(util.ndb_to_list(followees))
            
        self.response.out.write(template.render(values))
        
app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()
